package com.devbobcorn.donutopia.world.structure;

import java.util.Random;

import com.mojang.serialization.Codec;

import net.minecraft.util.Mirror;
import net.minecraft.util.RegistryKey;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Rotation;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.registry.Registry;
import net.minecraft.world.ISeedReader;
import net.minecraft.world.World;
import net.minecraft.world.gen.ChunkGenerator;
import net.minecraft.world.gen.Heightmap;
import net.minecraft.world.gen.feature.Feature;
import net.minecraft.world.gen.feature.NoFeatureConfig;
import net.minecraft.world.gen.feature.template.BlockIgnoreStructureProcessor;
import net.minecraft.world.gen.feature.template.PlacementSettings;
import net.minecraft.world.gen.feature.template.Template;

public class PagodaStructure extends Feature<NoFeatureConfig> {
	public PagodaStructure(Codec<NoFeatureConfig> CODEC) {
		super(CODEC);
	}

	@Override
	public boolean place(ISeedReader world, ChunkGenerator generator, Random random, BlockPos pos, NoFeatureConfig config) {
		int ci = (pos.getX() >> 4) << 4;
		int ck = (pos.getZ() >> 4) << 4;
		RegistryKey<World> dimensionType = world.getLevel().dimension();
		boolean dimensionCriteria = false;
		if (dimensionType == RegistryKey.create(Registry.DIMENSION_REGISTRY, new ResourceLocation("donutopia:donutopia")))
			dimensionCriteria = true;
		if (!dimensionCriteria)
			return false;
		if ((random.nextInt(1000000) + 1) <= 5000) {
			int count = random.nextInt(1) + 1;
			for (int a = 0; a < count; a++) {
				int i = ci + random.nextInt(16);
				int k = ck + random.nextInt(16);
				int j = world.getHeight(Heightmap.Type.OCEAN_FLOOR_WG, i, k);
				j -= 1;
				Rotation rotation = Rotation.values()[random.nextInt(3)];
				Mirror mirror = Mirror.values()[random.nextInt(2)];
				BlockPos spawnTo = new BlockPos(i + 0, j + -3, k + 0);
				
				Template template = world.getLevel().getStructureManager()
						.get(new ResourceLocation("donutopia", "pagoda"));
				if (template == null)
					return false;
				template.placeInWorld(world, spawnTo, new PlacementSettings().setRotation(rotation).setRandom(random).setMirror(mirror)
						.addProcessor(BlockIgnoreStructureProcessor.STRUCTURE_AND_AIR).setChunkPos(null).setIgnoreEntities(false),
						random);
			}
		}
		return true;
	}
}